package com.regex.web.baidu.ai;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * 网络图片获取byte流
 * @author ocean.regex
 *
 */
public class NetImageUtils {
	
	/**
	 * 网络图片获取byte流
	 * @param strUrl
	 * @return
	 */
	public static byte[] getImgerFormNetByUrl(String strUrl){
	    HttpURLConnection conn = null;
	    try {
	        URL url = new URL(strUrl);
	        conn = (HttpURLConnection) url.openConnection();
	        //conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //权限限制时可用此方法
	        conn.setRequestMethod("GET");
	        conn.setConnectTimeout(5*1000);
	        InputStream inputStream = conn.getInputStream();
	        byte[] btImg = toByteArray(inputStream);;
	        return  btImg;
	    }catch (Exception e){
	        e.printStackTrace();
	    }finally {
	        conn.disconnect();
	    }
	    return null;
	}
	
	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024*4];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
		}

}
